Lua

About

Basics

-- comment

--[[ 
    multiline comment
]]--

local number = 5

local text = "hello world"
local text2 = 'hello world'

local truth, lies = true, false

local nothing = nil

Functions

-- method 1
local function hello(name)
    print('hello', name)
end

-- method 2  (preferred)
local greet = function(name)
    print('hello ' .. name)
end
Multiple returns
local returns_four_values = function()
  return 1, 2, 3, 4
end

first, second, last = returns_four_values()

print("first: ", first)
print("second:", second)
print("last:  ", last)
-- the `4` is discarded
Multiple parameters
  • Using ...

local variable_arguments = function(...)
  local arguments = { ... }
  for i, v in ipairs({...}) do print(i, v) end
  return unpack(arguments)
end

print("===================")
print("1:", variable_arguments("hello", "world", "!"))
print("===================")
print("2:", variable_arguments("hello", "world", "!"), "<lost>")
Convention
  • Functions usually accept 1 Table as a parameter, where inside that table you pass names like default , other , etc.

local setup = function(opts)
  if opts.default == nil then
    opts.default = 17
  end

  print(opts.default, opts.other)
end

setup { default = 12, other = false}
setup { other = true}
OOP
local MyTable = {}

-- These are equivalent
function MyTable.something(self, ...) end
function MyTable:something(...) end
    -- "This is syntax sugar for `.` and `self`.

Table

As Lists
local list = { "first", 2, false, function() print("Fourth!") end }
print("Yup, 1-indexed:", list[1])
print("Fourth is 4...:", list[4]())
As Maps
local t = {
  literal_key = "a string",
  ["an expression"] = "also works",
  [function() end] = true
}

print("literal_key   : ", t.literal_key)
print("an expression : ", t["an expression"])
print("function() end: ", t[function() end])

Control Flows

for

local favorite_accounts = { "teej_dv", "ThePrimeagen", "terminaldotshop" }

for index = 1, #favorite_accounts do
  print(index, favorite_accounts[index])
end

for index, value in ipairs(favorite_accounts) do
  print(index, value)
end

if

local function action(loves_coffee)
  if loves_coffee then
    print("Check out `ssh terminal.shop` - it's cool!")
  else
    print("Check out `ssh terminal.shop` - it's still cool!")
  end
end

-- "falsey": nil, false
action() -- Same as: action(nil)
action(false)

-- Everything else is "truthy"
action(true)
action(0)
action({})

Modules

  • "files are just big Lua functions".

-- foo.lua
local M = {}
M.cool_function = function() end
return M

-- bar.lua
local foo = require('foo')
foo.cool_function()

Metatables

local vector_mt = {}
vector_mt.__add = function(left, right)
  return setmetatable({
    left[1] + right[1],
    left[2] + right[2],
    left[3] + right[3],
  }, vector_mt)
end

local v1 = setmetatable({ 3, 1, 5 }, vector_mt)
local v2 = setmetatable({ -3, 2, 2 }, vector_mt)
local v3 = v1 + v2
vim.print(v3[1], v3[2], v3[3])
vim.print(v3 + v3)

Game Dev

Love2D